package cn.hl.exception;

import cn.hl.enums.GlobalExceptionCode;
import cn.hl.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult customException(Exception e) {
        e.printStackTrace();
        log.error("全局异常：GlobalExceptionHandler,错误信息为：{}",e.getMessage());
        return JSONResult.error(GlobalExceptionCode.FAIL);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult customException(GlobalCustomException e) {
        e.printStackTrace();
        log.error("全局异常：GlobalCustomException,错误信息为：{}",e.getMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.error("全局异常：MethodArgumentNotValidException,错误信息为：{}",e.getMessage());
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(obj -> {
            String defaultMessage = obj.getDefaultMessage();
            sb.append(defaultMessage + ";");
        });
        return JSONResult.error(sb.toString(),"-2");
    }

}
